package com.hexin.download.service.impl;

import com.hexin.download.service.Download;
import com.hexin.download.service.OnDownloadListener;
import com.hexin.download.util.Constants;
import com.hexin.download.util.FileUtils;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class DownloadImpl implements Download {
    private static Logger logger = LoggerFactory.getLogger(DownloadImpl.class);
    private String url;
    private String name;
    private String saveDir;
    private OnDownloadListener onDownloadListener;
    public DownloadImpl(String url, String name, String saveDir) {
        this.url = url;
        this.name = name;
        this.saveDir = saveDir;
    }

    /**
     * @param url      下载连接
     * @param saveDir  储存下载文件的SDCard目录
     */
    public String download(final String url, final String name, final String saveDir) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .build();
        final Call call = okHttpClient.newCall(request);
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            String savePath = isExistDir(saveDir);
            File file = new File(savePath, name);
            fos = new FileOutputStream(file);
            byte[] buf = new byte[2048];
            int len;
            Response response = call.execute();
            fos = new FileOutputStream(file);
            if (response.code() == 200){
                is = response.body().byteStream();
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
            } else {
                FileUtils.logRecord(name+" "+url+"\r\n",Constants.VIDEO_LOG_PATH);
                return name + "-----下载失败";
            }
        } catch (Exception e) {
            logger.error(name + "下载失败：exceptionMessage：{}",e.getMessage());
            FileUtils.logRecord(name+" "+url+"\r\n",Constants.VIDEO_LOG_PATH);
            return name + "-----下载失败";
        } finally {
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    logger.error(name + "download文件输入流关闭失败：exceptionMessage：{}",e.getMessage());
                }
            }
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    logger.error(name + "download文件输出流关闭失败：exceptionMessage：{}",e.getMessage());
                }
            }
        }
        logger.info(name+ "-------下载成功");
        return name+ "-------下载成功";
    }

    /**
     * @param saveDir
     * @return
     * @throws IOException 判断下载目录是否存在
     */
    public static String isExistDir(String saveDir) throws IOException {
        // 下载位置
        File fileDir = new File(saveDir);
        if (fileDir.exists() && fileDir.isDirectory()){
            return saveDir;
        }
        if (!fileDir.exists()){
            if (fileDir.mkdirs()){
               logger.info("创建目录成功");
                return saveDir;
            } else {
                logger.error("创建目录失败");
                throw new IOException("创建文件目录:"+ saveDir +"失败");
            }
        }
        return saveDir;
    }

    @Override
    public String download() {
        logger.info(name + "开始下载....");
        return download(url,name,saveDir);
    }
}